package cn.net.shuxing.yifu.common.front.controller;

import cn.net.shuxing.yifu.common.bean.ContentSys;
import cn.net.shuxing.yifu.common.bean.UserPassword;
import cn.net.shuxing.yifu.common.bean.UserRealInfo;
import cn.net.shuxing.yifu.common.constant.CodeConst;
import cn.net.shuxing.yifu.common.constant.OssConstant;
import cn.net.shuxing.yifu.common.dto.BaseDto;
import cn.net.shuxing.yifu.common.service.*;
import cn.net.shuxing.yifu.common.util.JedisUtil;
import cn.net.shuxing.yifu.common.util.MD5Util;
import cn.net.shuxing.yifu.common.util.RedisKeyCreator;
import cn.net.shuxing.yifu.common.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.cloudauth.model.v20180916.*;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import cn.net.shuxing.yifu.common.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/front/common")
public class FrontCommenController {

    @Autowired
    private UserPasswordService userPasswordService;

    @Autowired
    private FaceVerifyService faceVerifyService;

    @Autowired
    private JedisUtil jedisUtil;

    @Autowired
    private UserRealInfoService userRealInfoService;

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Autowired
    private OssCommonService ossCommonService;


    @Autowired
    private ContentSysService contentSysService;

//    @RequestMapping("/deal/verify")
//    public BaseDto ()
//    {
//
//    }

    /**
     * 获取该用户资金密码是否启用
     *
     * @param userId
     * @return
     */
    @ApiOperation(value = "获取该用户资金密码是否启用")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Integer", paramType = "query")
    @RequestMapping("/capitalPassword/required")
    public BaseDto isCapitalPasswordRequired(Integer userId) {

        UserPassword userPassword = userPasswordService.getByPrimaryKey(userId);
        if (userPassword == null) {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("请先设置资金密码");
            return baseDto;
        }

        Integer required = userPassword.getRequired();
        BaseDto baseDto = new BaseDto();
        baseDto.setData(required);
        return baseDto;
    }

    /**
     * 验证输入的资金密码是否正确
     *
     * @param userId
     * @param capitalPassword
     * @return
     */
    @RequestMapping("/capitalPassword/verify")
    public BaseDto verifyCapitalPassword(Integer userId, String capitalPassword, String key) {
        Jedis jedis1 = jedisUtil.getJedis();
        String errorCount = jedis1.get(RedisKeyCreator.capitalPasswordErrorCount(userId));
        jedis1.close();
        if (StringUtils.hasText(errorCount)) {
            if (Integer.valueOf(errorCount) >= 3) {
                return BaseDto.error("交易密码输入次数过多,请重设资金密码");
            }
        }
        UserPassword userPassword = userPasswordService.getByPrimaryKey(userId);
        if (userPassword == null) {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("请先设置资金密码");
            return baseDto;
        }

        if (!MD5Util.md5(capitalPassword).equals(userPassword.getCapitalPassword())) {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("密码错误");
            //Jedis //jedis = jedisUtil.getJedis();
            jedisUtil.incr(RedisKeyCreator.capitalPasswordErrorCount(userId));
            //jedisUtil.close();
            return baseDto;
        }

        //Jedis //jedis = jedisUtil.getJedis();
        jedisUtil.del(RedisKeyCreator.capitalPasswordErrorCount(userId));
        jedisUtil.incr(key);
        jedisUtil.set(RedisKeyCreator.transferKey(userId),"3");
        //jedisUtil.close();
        BaseDto baseDto = new BaseDto();
        baseDto.setData("success");
        return baseDto;
    }

    @RequestMapping("/face/verify/token")
    public BaseDto getFaceVerifyToken(Integer userId, String transferKey) {
        UserRealInfo userRealInfo = userRealInfoService.getByPrimaryKeyWithoutComplete(userId);
        if (userRealInfo == null || userRealInfo.getVerified() == 0) {
            return BaseDto.error("请先完成实名认证");
        }

        //创建DefaultAcsClient实例并初始化
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou",             //默认
                accessKeyId,         //您的Access Key ID
                accessKeySecret);    //您的Access Key Secret
        IAcsClient client = new DefaultAcsClient(profile);
        String biz = "New"; //您在控制台上创建的、采用FVBioOnly认证方案的认证场景标识, 创建方法：https://help.aliyun.com/document_detail/59975.html
        String ticketId = transferKey; //认证ID, 由使用方指定, 发起不同的认证任务需要更换不同的认证ID
        String token = null; //认证token, 表达一次认证会话
        int statusCode = -1; //-1 未认证, 0 认证中, 1 认证通过, 2 认证不通过
//1. 服务端发起认证请求, 获取到token
//GetVerifyToken接口文档：https://help.aliyun.com/document_detail/57050.html
        GetVerifyTokenRequest getVerifyTokenRequest = new GetVerifyTokenRequest();
        getVerifyTokenRequest.setBiz(biz);
        getVerifyTokenRequest.setTicketId(ticketId);
        getVerifyTokenRequest.setMethod(MethodType.POST);
//通过binding参数传入业务已经采集的认证资料，其中人像留底照片为必要字段
//请控制单张图片大小在 2M 内，避免拉取超时
        getVerifyTokenRequest.setBinding("{\"FaceRetainedPic\": \"" + ossCommonService.getUrl(OssConstant.ossBucketName, userRealInfo.getTakingCardPhoto()) + "\"}");
        try {
            GetVerifyTokenResponse response = client.getAcsResponse(getVerifyTokenRequest);
            token = response.getData().getVerifyToken().getToken(); //token默认30分钟时效，每次发起认证时都必须实时获取
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return BaseDto.ok(token);
    }

    /**
     * 人脸识别
     *
     * @param userId 用户id
     * @param key    交易key
     * @return
     */
    @RequestMapping("/face/verify")
    @ResponseBody
    public BaseDto faceVerify(Integer userId, String token, String key) {
        /** 测试过程暂不使用人脸识别,正式部署时开启 **/
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou",             //默认
                accessKeyId,         //您的Access Key ID
                accessKeySecret);    //您的Access Key Secret
        IAcsClient client = new DefaultAcsClient(profile);
        //7. 服务端获取认证资料
//GetMaterials接口文档：https://help.aliyun.com/document_detail/57641.html
        String biz = "New";
        //6. 服务端查询认证状态(客户端回调中也会携带认证状态, 但建议以服务端调接口确认的为准)
//GetStatus接口文档：https://help.aliyun.com/document_detail/57049.html
        GetStatusRequest getStatusRequest = new GetStatusRequest();
        getStatusRequest.setBiz(biz);
        getStatusRequest.setTicketId(key);
        int statusCode = -1;
        try {
            GetStatusResponse response = client.getAcsResponse(getStatusRequest);
            statusCode = response.getData().getStatusCode();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        GetMaterialsRequest getMaterialsRequest = new GetMaterialsRequest();
        getMaterialsRequest.setBiz(biz);
        getMaterialsRequest.setTicketId(key);
//        if( 1 == statusCode || 2 == statusCode ) { //认证通过or认证不通过
//            try {
//                GetMaterialsResponse response = client.getAcsResponse(getMaterialsRequest);
//                //后续业务处理
//                System.out.println(JSON.toJSONString(response));
//            } catch (ServerException e) {
//                e.printStackTrace();
//            } catch (ClientException e) {
//                e.printStackTrace();
//            }
//        }
        if (statusCode == 1) {
            //Jedis //jedis = jedisUtil.getJedis();
            jedisUtil.incr(key);
            //jedisUtil.close();
            return BaseDto.ok("success");
        } else {
            if (statusCode != 2)
                System.out.println("人脸识别错误状态码:" + statusCode);
            return BaseDto.error("fail");
        }

    }

    /**
     * 获取交易key
     *
     * @param userId 用户id
     * @return
     */
    @RequestMapping("/transfer/key")
    public BaseDto getTransferKey(Integer userId) {
        String key = RedisKeyCreator.transferKey(userId);
        //Jedis //jedis = jedisUtil.getJedis();
        jedisUtil.set(key,"1");
        jedisUtil.expire(key,15 * 60);
//        jedisUtil.setex(key, 15 * 60, "1");
        //jedisUtil.close();
        return BaseDto.ok(key);
    }

    @RequestMapping("/content/link/parse")
    public BaseDto parseLink(String link) throws UnknownHostException {
//        String prefix = "inlineLink-";
//        String url = link;
//        if (link.startsWith(prefix))
//        {
//            ContentSys contentSys = contentSysService.getByInlienLink(link);
//            if (contentSys != null)
//            {
//                contentSys.setSysSkimNum(contentSys.getSysSkimNum()+1);
//                contentSysService.update(contentSys);
//            }
//            String objectName = link.substring(prefix.length());
//            url = ossCommonService.getUrl(OssConstant.ossBucketName,objectName);
//        }
        String prefix = "http://";
        String prefix1 = "https://";
        String url = link;
        if (!(link.startsWith(prefix) || link.startsWith(prefix1))) {
            return BaseDto.ok("http://47.98.205.250" + url);
//            return BaseDto.ok("http://" + InetAddress.getLocalHost().getHostAddress() + ":8080" + url);
        }
        return BaseDto.ok(url);
    }
}